package com.shujia.service;

import com.shujia.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService {

    // 使用SpringBoot提供给我们的JDBC类
    // 使用Autowired创建了一个对象，并注入进来使用
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //查询所有部门的信息
    @Override
    public List<Dept> getAllCusBaseInfo() {
        //查询部门信息
        List<Map<String,Object>> list=jdbcTemplate.queryForList("select * from dept");
        List<Dept> cusBaseInfoList=new ArrayList<>();
        for (Map<String,Object> map:list ) {
            Dept cusBaseInfo=new Dept();
            //部门id
            cusBaseInfo.setDeptno((Integer) (map.get("deptno")));

            cusBaseInfo.setDname(map.get("dname").toString());

            cusBaseInfo.setLoc(map.get("loc").toString());
            cusBaseInfoList.add(cusBaseInfo);
        }
        return cusBaseInfoList;
    }

    //保存一个部门信息
    @Override
    public String saveDeptInfo(Dept dept) {
        String sql="insert into dept(deptno,dname,loc) values(?,?,?)";
        int count = jdbcTemplate.update(sql, new Object[]{dept.getDeptno(),
                dept.getDname(),
                dept.getLoc(),}, new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR});
        //获取信息
        return count==1?"数据保存成功！！":"数据保存失败！！";
    }

    //根据部门编号查询部门信息
    @Override
    public Dept getDeptByNo(int deptNo) {
        Map<String,Object> map=jdbcTemplate.queryForMap("select * from dept where deptno = ?",deptNo);
        Dept cusBaseInfo=new Dept();

        cusBaseInfo.setDeptno((Integer)(map.get("deptno")));

        cusBaseInfo.setDname(map.get("dname").toString());

        cusBaseInfo.setLoc(map.get("loc").toString());
        return cusBaseInfo;
    }
}
